# !/usr/bin/env python
# -*- coding: utf-8 -*-

import struct


def color24_to_color16(data):
    """
    24位真彩转16位真彩
    :param data:
    :return:
    """
    rdata = []
    i = 0
    while i < len(data):
        (r, g, b) = struct.unpack("!3B", data[i:i + 3])
        r = (r >> 3)
        g = (g >> 2)
        b = (b >> 3)
        r_l = (r << 3) + (g >> 3)
        r_r = ((g & 0b111) << 5) + b
        if r_l > 255 or r_r > 255:
            raise Exception
        rdata.append(r_l)
        rdata.append(r_r)
        i += 3
    return struct.pack("!%sB" % len(rdata), *rdata)
